﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Web;

namespace Web.MyApi
{
    /// <summary>
    /// CheckCode 的摘要说明
    /// </summary>
    public class CheckCode : IHttpHandler, System.Web.SessionState.IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            //定义颜色
            Color[] colors = new Color[] { Color.Red, Color.Green, Color.Yellow, Color.Blue, Color.AliceBlue, Color.Gray, Color.SkyBlue, Color.Brown };
            //定义字符
            List<char> charList = new List<char>();
            //放入小写字母
            for (int i = 'a'; i <= 'z'; i++)
            {
                charList.Add((char)i);
            }
            //放入大写字母
            for (int i = 'A'; i <= 'Z'; i++)
            {
                charList.Add((char)i);
            }
            //放入数字
            for (int i = '0'; i <= '9'; i++)
            {
                charList.Add((char)i);
            }
            //创建图片
            Image img = new Bitmap(100, 36);
            //创建画布
            Graphics g = Graphics.FromImage(img);
            g.Clear(Color.Wheat);
            //创建随机数对象
            Random rand = new Random();
            //随机产生4个字符
            char num1 = charList[rand.Next(0, charList.Count)];
            char num2 = charList[rand.Next(0, charList.Count)];
            char num3 = charList[rand.Next(0, charList.Count)];
            char num4 = charList[rand.Next(0, charList.Count)];
            //生成验证码
            string yzCode = string.Format("{0}{1}{2}{3}", num1, num2, num3, num4);
            //保存到Session用于比较(实现接口IRequiresSessionState)
            context.Session["checkCode"] = yzCode;
            //创建字体
            Font font = new Font("宋体", 24);
            //创建画笔四个字符随机颜色4个画笔
            Brush b1 = new SolidBrush(colors[rand.Next(0, colors.Length)]);
            //绘制字符串(计算位置)
            g.DrawString(num1 + "", font, b1, 7, -3);
            Brush b2 = new SolidBrush(colors[rand.Next(0, colors.Length)]);
            //绘制字符串(计算位置)
            g.DrawString(num2 + "", font, b2, 26, -9);
            Brush b3 = new SolidBrush(colors[rand.Next(0, colors.Length)]);
            //绘制字符串(计算位置)
            g.DrawString(num3 + "", font, b3, 50, 0);
            Brush b4 = new SolidBrush(colors[rand.Next(0, colors.Length)]);
            //绘制字符串(计算位置)
            g.DrawString(num4 + "", font, b4, 70, -7);
            //设置输出格式
            context.Response.ContentType = "image/jpeg";
            //保存图片的输出流
            img.Save(context.Response.OutputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            //释放画布
            g.Dispose();
            //释放图片
            img.Dispose();

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}